# coding=utf-8
"""
Copyright (c) Huawei Technologies Co., Ltd. 2020-2028. All rights reserved.
Description:
FileName：stop.py
Author: h00568282/huangbin 
Create Date: 2025/9/18 16:52
Notes:

"""
from typing import List

import psutil

from sys_intd.exceptions import MCPServerStopError
from sys_intd.manager import McpServerManager

WorkingDirectory = "/usr/lib/euler-copilot-framework/mcp_center"


def stop_server_from_mcp_center(server_name: str = "cache-miss-audit"):
    mcp_server_manager = McpServerManager()
    server_config = mcp_server_manager.get_server(server_name)
    python_cmd: List = [server_config.command, *server_config.args]
    output_lines = [f'''\n[bold cyan]Prepare stop server '{server_name}'.\n''']

    if len(python_cmd) < 2:
        raise MCPServerStopError(f'''\n[bold cyan]'{server_name}' is not running, please check it.\n''')

    server_path = python_cmd[1]
    killed = False

    for proc in psutil.process_iter(['pid', 'name', 'cmdline', 'exe']):
        try:
            cmdline = proc.info['cmdline']  # 进程启动命令行，是一个列表，如 ['python3', 'xxx.py']
            process_name = proc.info['name']
            if not cmdline or len(cmdline) < 2:
                continue
            if process_name != 'python3' and process_name != 'python':
                continue

            launched_script = cmdline[1] if len(cmdline) > 1 else ""

            if launched_script.endswith(server_path):
                output_lines.append(
                    f'''[bold]Find target process, pid: {proc.info['pid']}, startup cmd: {' '.join(cmdline)}''')
                proc.terminate()
                output_lines.append(
                    f'''[bold]Sending SIGTERM signal to pid: {proc.info['pid']}''')
                killed = True

                try:
                    proc.wait(timeout=3)
                except psutil.TimeoutExpired:
                    proc.kill()
                    raise MCPServerStopError(
                        f'''[bold]Process do not response to SIGTERM, force sending SIGKILL to pid:{proc.info['pid']}.''')

        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            continue

    if not killed:
        output_lines.append(
            f'''\n[bold cyan]Not Find running target server {server_name}, please check server {server_name} status.\n''')
    else:
        output_lines.append(f'''\n[bold cyan]Server {server_name} has been stopped.\n''')

    return output_lines


def stop(server_name: str = "cache-miss-audit"):
    output_lines = stop_server_from_mcp_center(server_name)

    return output_lines


def main():
    stop()


if __name__ == "__main__":
    main()
